using System;
using System.Reflection.Emit;
using Pine.Core;
using Pine.SourceParser.Tree;

namespace Pine.CodeGen
{
	public static class ArrayConstantCodeGenerator
	{
		public static void GenerateBytecode(Context ctx, Expression expr, LocalBuilder lb) {
			ctx.il.Emit(OpCodes.Newobj, typeof(ValueList).GetConstructor(Type.EmptyTypes));
			ctx.il.Emit(OpCodes.Stloc, lb);
			
			ArrayConstant array = (ArrayConstant) expr;
			
			foreach (ArrayMember member in array.arrayMembers) {
				LocalBuilder key = ctx.il.DeclareLocal(typeof(Value));
				member.key.GenerateBytecode(ctx, key);
				LocalBuilder value = ctx.il.DeclareLocal(typeof(Value));
				member.value.GenerateBytecode(ctx, value);
				ctx.il.Emit(OpCodes.Ldloc, lb);
				ctx.il.Emit(OpCodes.Ldloc, key);
				ctx.il.Emit(OpCodes.Ldloc, value);
				ctx.il.Emit(OpCodes.Callvirt, typeof(Value).GetMethod("SetArrayElement"));
			}
		}
	}
}

